import easygui as eg
from database import Database
from main_app import show_main_app


def show_login_window():
    db = Database()

    while True:
        # 登录表单
        choices = ["登录", "注册", "退出"]
        choice = eg.buttonbox("旅行社管理系统", "欢迎", choices)

        if choice == "退出" or choice is None:
            break
        elif choice == "登录":
            handle_login(db)
        elif choice == "注册":
            handle_register(db)

    db.close()


def handle_login(db):
    """处理用户登录"""
    while True:
        fields = ["用户名", "密码"]
        values = eg.multpasswordbox("旅行社管理系统 - 登录", "登录", fields)

        if values is None:  # 用户点击取消
            break

        username, password = values

        if not username or not password:
            eg.msgbox("请输入用户名和密码", "错误")
            continue

        # 验证登录
        hashed_password = Database.hash_password(password)
        query = "SELECT * FROM Users WHERE Username = ? AND Password = ?"
        user = db.execute_query(query, (username, hashed_password))

        if user and len(user) == 1:
            user = user[0]
            show_main_app(db, user)
            return True
        else:
            eg.msgbox("用户名或密码错误", "登录失败")
            return False


def handle_register(db):
    """处理用户注册"""
    while True:
        # 基本信息
        fields = [
            "用户名*",
            "密码*",
            "确认密码*",
            "用户类型(admin/guide/tourist)*",
            "真实姓名",
            "电子邮箱",
            "联系电话"
        ]
        values = eg.multenterbox("填写注册信息（带*的为必填项）", "用户注册", fields)

        if values is None:  # 用户点击取消
            break

        username, password, confirm, user_type, realname, email, phone = values

        # 验证必填字段
        if not all([username, password, confirm, user_type]):
            eg.msgbox("带*的字段为必填项", "错误")
            continue

        if password != confirm:
            eg.msgbox("两次输入的密码不一致", "错误")
            continue

        if user_type not in ['admin', 'guide', 'tourist']:
            eg.msgbox("用户类型必须是admin/guide/tourist", "错误")
            continue

        try:
            # 检查用户名是否已存在
            if db.execute_query("SELECT 1 FROM Users WHERE Username = ?", (username,)):
                eg.msgbox("用户名已存在", "错误")
                continue

            # 开始事务
            cursor = db.connection.cursor()

            # 插入用户基本信息
            hashed_password = Database.hash_password(password)
            cursor.execute("""
                INSERT INTO Users (Username, Password, UserType, RealName, Email, Phone, Status)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            """, (username, hashed_password, user_type, realname, email, phone, 0 if user_type == 'guide' else 1))

            # 获取新用户ID
            user_id = cursor.execute("SELECT SCOPE_IDENTITY()").fetchone()[0]

            # 根据用户类型插入到相应表
            if user_type == 'guide':
                add_guide_info(db, cursor, user_id)
            elif user_type == 'tourist':
                add_tourist_info(db, cursor, user_id)

            # 提交事务
            db.connection.commit()

            eg.msgbox("注册成功！请登录", "成功")
            return True

        except Exception as e:
            db.connection.rollback()
            eg.msgbox(f"注册失败: {str(e)}", "错误")
            return False


def add_guide_info(db, cursor, user_id):
    """添加导游额外信息"""
    fields = ["导游证号*", "性别", "年龄", "从业年限", "专长", "简介"]
    values = eg.multenterbox("填写导游信息（带*的为必填项）", "导游信息", fields)

    if not values or not values[0]:  # 导游证号为必填
        raise ValueError("导游证号为必填项")

    license_no, gender, age, exp, specialty, intro = values

    cursor.execute("""
        INSERT INTO Guides (UserID, LicenseNumber, Gender, Age, Experience, Specialty, Introduction)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    """, (user_id, license_no, gender, age, exp, specialty, intro))


def add_tourist_info(db, cursor, user_id):
    """添加游客额外信息"""
    fields = ["身份证号*", "性别", "年龄", "地址", "紧急联系人", "紧急联系电话"]
    values = eg.multenterbox("填写游客信息（带*的为必填项）", "游客信息", fields)

    if not values or not values[0]:  # 身份证号为必填
        raise ValueError("身份证号为必填项")

    id_no, gender, age, address, emergency_contact, emergency_phone = values

    cursor.execute("""
        INSERT INTO Tourists (UserID, IDNumber, Gender, Age, Address, EmergencyContact, EmergencyPhone)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    """, (user_id, id_no, gender, age, address, emergency_contact, emergency_phone))